package main

import (
	"demo3/entity"
	"encoding/json"
	"fmt"
	"gitee.com/baizhige/mongong-go"
	"gitee.com/baizhige/mongong-go/db"
	"gitee.com/baizhige/mongong-go/processor"
	"gitee.com/baizhige/mongong-go/query"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

func main() {
	// 演示数据库初始化
	err := db.InitDB("mongodb://root:cT93YrhLJt3nwDuX@8.134.198.135:6664/", "demo1")
	if err != nil {
		return
	}
	//初始化插件
	processor.Register(processor.QueryType, processor.DecProcessor{})

	// 基础查询
	uid, _ := primitive.ObjectIDFromHex("66a5e7fdfe8ef5eb83d979c1")
	filter := entity.UserCard{UID: uid}
	result, err := mongong.Coll[entity.UserCard]().Find(filter) //查询
	if err != nil {
		fmt.Println(err)
		return
	}
	printArr(result)

	userDomain := mongong.Coll[entity.User]()
	// Query查询
	fmt.Println("开始演示 Query 查询")
	res, _ := userDomain.Query(query.Eq("name", "demo2-user1"))
	printArr(res)

	// Query分页
	fmt.Println("开始演示 Query 分页")
	pageData, err := userDomain.QueryPage(
		query.
			Lt("createtime", time.Now()).
			PageInfo(1, 2).
			DESC("name"),
	)

	marshal, _ := json.Marshal(pageData)
	fmt.Println(string(marshal))

	// 测试 $in
	fmt.Println("开始演示 Query in")
	res, _ = userDomain.Query(query.In("name", "demo2-user1", "demo3-user9"))
	printArr(res)
}

func printArr[T any](arr []T) {
	fmt.Println("len:", len(arr))
	for i, item := range arr {
		marshal, err := json.Marshal(item)
		if err != nil {
			continue
		}
		fmt.Println(i, ":", string(marshal))
	}
}
